/**
 * ==================================
 * 高频治理排行
 * ==================================
 */
import { useRequest } from 'ahooks'
import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useMemo,
  useRef,
  useState
} from 'react'

import { Tb } from '../../../BigScreenBase/ModuleTitle'
import WordHScroll from '../../../BigScreenWarn/Components/WordHScroll'
import DisplayCard from '../../Components/DisplayCard'
import ListRanking, { ColumnType } from '../../Components/ListRanking'
import rank1 from '../../images/yellowRank1.png'
import rank2 from '../../images/yellowRank2.png'
import rank3 from '../../images/yellowRank3.png'
import {
  getNameFromDataType,
  getTypeNameFromDataType
} from '../RiskRanking/data'
import {
  HighFrequencyTreatmentRankingDataResponse,
  getHighFrequencyTreatmentRankingData,
  highFrequencyTreatmentRankingTabList
} from './data'

export type HighFrequencyTreatmentRankingProps = {
  entId: string
}

export type HighFrequencyTreatmentRankingRef = {
  onRefresh: () => void
}

const DATA_TYPE_REFRESH_PER_MS = 60 * 1000

const rankImg = [rank1, rank2, rank3]

const HighFrequencyTreatmentRanking = forwardRef<
  HighFrequencyTreatmentRankingRef,
  HighFrequencyTreatmentRankingProps
>(({ entId }, ref) => {
  const currentDataTypeTabIndexRef = useRef<number>(0)
  const [activeDataTypeTabKey, setActiveDataTypeTabKey] = useState<number>(3)
  const timerRef = useRef<any>(null)

  const [refresh, setRefresh] = useState<number>(0)

  const [tableData, setTableData] = useState<
    HighFrequencyTreatmentRankingDataResponse[]
  >([])

  const columns: ColumnType<HighFrequencyTreatmentRankingDataResponse>[] =
    useMemo(() => {
      return [
        {
          title: '排行',
          key: 'index',
          width: 40,
          align: 'center',
          render(_, record, index) {
            return index < 3 ? (
              <div style={{ height: 16 }}>
                <img src={rankImg[index]} style={{ width: 16, height: 16 }} />
              </div>
            ) : (
              index + 1
            )
          }
        },
        {
          title: getNameFromDataType(activeDataTypeTabKey),
          key: 'name',
          width: 200,
          align: 'left',
          render(_, record, index) {
            return (
              <div
                style={{
                  width: '100%',
                  paddingRight: 16,
                  overflow: 'hidden',
                  whiteSpace: 'nowrap',
                  color: index < 3 ? '#FFB13B' : undefined
                }}
              >
                <WordHScroll>
                  <span>{record?.name}</span>
                </WordHScroll>
              </div>
            )
          }
        },
        {
          title: getTypeNameFromDataType(activeDataTypeTabKey),
          key: 'typeName',
          width: 100,
          render(_, record, index) {
            return (
              <div
                style={{
                  width: '100%',
                  overflow: 'hidden',
                  whiteSpace: 'nowrap'
                }}
              >
                <WordHScroll>
                  <span>{record?.typeName}</span>
                </WordHScroll>
              </div>
            )
          }
        },
        {
          title: '治理次数',
          key: 'number',
          width: 62
        }
      ]
    }, [activeDataTypeTabKey])

  useImperativeHandle(ref, () => ({
    onRefresh: () => {
      setRefresh(Math.random())
    }
  }))

  useEffect(() => {
    startInterval()
    return () => {
      stopInterval()
    }
  }, [])

  useRequest(
    () => {
      return getHighFrequencyTreatmentRankingData({
        entId,
        type: activeDataTypeTabKey,
        topNum: 10
      })
    },
    {
      onSuccess(data) {
        if (data) {
          setTableData(data)
        }
      },
      refreshDeps: [entId, activeDataTypeTabKey]
    }
  )

  /**
   * 高频治理排行标题tab - 切换事件
   *
   * @param option
   */
  const onModuleTitleTabChange = (option: Tb) => {
    const newIndex = highFrequencyTreatmentRankingTabList.findIndex(
      (item) => item.value === option.value
    )

    currentDataTypeTabIndexRef.current = newIndex

    setActiveDataTypeTabKey(option.value as number)

    setRefresh(Math.random())
  }

  /**
   * 高频治理排行标题tab - 定时器
   */
  function startInterval() {
    stopInterval()
    timerRef.current = setInterval(() => {
      const newIndex =
        (currentDataTypeTabIndexRef.current + 1) %
        highFrequencyTreatmentRankingTabList.length
      const newValue = highFrequencyTreatmentRankingTabList[newIndex].value

      currentDataTypeTabIndexRef.current = newIndex

      setActiveDataTypeTabKey(newValue as number)
    }, DATA_TYPE_REFRESH_PER_MS)
  }

  function stopInterval() {
    timerRef.current && clearInterval(timerRef.current)
  }

  /**
   * 高频治理排行标题tab - 移入事件
   */
  function onModuleTitleTabMouseEnter() {
    stopInterval()
  }

  /**
   * 高频治理排行标题tab - 移出事件
   */
  function onModuleTitleTabMouseLeave() {
    startInterval()
  }

  return (
    <DisplayCard
      title="高频治理排行"
      height={431}
      moduleTitleTabList={highFrequencyTreatmentRankingTabList}
      onModuleTitleTabChange={onModuleTitleTabChange}
      onModuleTitleTabMouseEnter={onModuleTitleTabMouseEnter}
      onModuleTitleTabMouseLeave={onModuleTitleTabMouseLeave}
      activeTabKey={activeDataTypeTabKey}
      bodyStyle={{
        height: 'calc(100% - 42px)'
      }}
    >
      <ListRanking
        // key={refresh}
        dataSource={tableData}
        columns={columns}
        rgbColor="255,177,59"
        emptyText="暂无高频治理排行"
      />
    </DisplayCard>
  )
})

export default HighFrequencyTreatmentRanking
